<?php

namespace App\Services;

use Illuminate\Http\Request;
use OSS\OssClient;

class UploadService
{

    private $accessKeyId = "LTAI4G4kftXfdJyf3KjGbQG1";
    private $accessKeySecret = "V35KBKWNBtDUY9VSVcuMJ3M1RyOXhf";
    private $endpoint = "https://oss-cn-shanghai.aliyuncs.com";
    private $outEndpoint = "https://oss-cn-shanghai.aliyuncs.com";
    private $securityToken = "";
    private $bucket = "xpel-dengwho";

    public function __construct()
    {
    }

    /**
     * 上传
     *
     * @param Request $request
     * @return string|mixed
     */
    public function upload(Request $request)
    {
        $file = $request->file('file');
        $extension = $file->getClientOriginalExtension();
        $fileName = $file->getClientOriginalName();
        if (!in_array(strtolower($extension), ['jpg', 'jpeg', 'png', 'gif'])) {
            throw new \Exception('图片格式错误');
        }

        $file_name = date('Ym') . '/' . md5($fileName . date('YmdHis') . mt_rand(1111111, 9999999)) . '.' . $extension;
        $imageUrl = $this->uploadAliOss(file_get_contents($file->getRealPath()), $file_name);
        if (empty($imageUrl['oss-request-url'])) {
            throw new \Exception('上传失败');
        }

        return str_replace('https://xpel-dengwho.oss-cn-shanghai.aliyuncs.com', 'https://image-xpel.dengwho.com', $imageUrl['oss-request-url']);
    }

    public function uploadVideo(Request $request)
    {
        /*$host = "https://xpel-dengwho.oss-cn-shanghai.aliyuncs.com";

        $now = time();
        $expire = 10; //设置该policy超时时间是10s. 即这个policy过了这个有效时间，将不能访问
        $end = $now + $expire;
        $expiration = $this->gmtIso8601($end);

        $dir = 'videos/'. date('Ym') . '/';//文件在oss中保存目录

        //最大文件大小.用户可以自己设置
        $conditions[] = ['content-length-range', 0, 1048576000];

        //表示用户上传的数据,必须是以$dir开始, 不然上传会失败,这一步不是必须项,只是为了安全起见,防止用户通过policy上传到别人的目录
        $start = array(0=>'starts-with', 1=>'$key', 2=>$dir);
        $conditions[] = $start;

        $arr = array('expiration'=>$expiration,'conditions'=>$conditions);
        $policy = json_encode($arr);
        $base64Policy = base64_encode($policy);
        $stringToSign = $base64Policy;
        $signature = base64_encode(hash_hmac('sha1', $stringToSign, $this->accessKeySecret, true));
        $fileName = substr(md5(uniqid(microtime() . rand(0, 999), true)), 8, 16) . '.' . $fileSuffix;

        return [
            'access_id' => $this->accessKeyId,
            'host'  => $host,
            'policy' => $base64Policy,
            'signature' => $signature,
            'expire'    => $end,
            'dir'   => $dir,
            'file_name' =>  $dir . $fileName,
        ];*/
        $file = $request->file('file');
        $extension = $file->getClientOriginalExtension();
        $fileName = $file->getClientOriginalName();
        if (!in_array(strtolower($extension), ["mp4", "avi"])) {
            throw new \Exception('视频格式错误');
        }

        $file_name = date('Ym') . '/' . md5($fileName . date('YmdHis') . mt_rand(1111111, 9999999)) . '.' . $extension;
        $imageUrl = $this->uploadAliOss(file_get_contents($file->getRealPath()), $file_name);
        if (empty($imageUrl['oss-request-url'])) {
            throw new \Exception('上传失败');
        }

        return str_replace('https://xpel-dengwho.oss-cn-shanghai.aliyuncs.com', 'https://image-xpel.dengwho.com', $imageUrl['oss-request-url']);
    }

    private function gmtIso8601($time) {
        $dtStr = date("c", $time);
        $mydatetime = new \DateTime($dtStr);
        $expiration = $mydatetime->format(\DateTime::ISO8601);
        $pos = strpos($expiration, '+');
        $expiration = substr($expiration, 0, $pos);
        return $expiration."Z";
    }

    public function uploadAliOss($file, $fileName)
    {
        $ossClient = new OssClient($this->accessKeyId, $this->accessKeySecret, $this->endpoint);
        $ossClient->createBucket($this->bucket, OssClient::OSS_ACL_TYPE_PUBLIC_READ);
        $ossClient->setTimeout(3600);
        $ossClient->setConnectTimeout(10);
        return $ossClient->putObject($this->bucket, $fileName, $file);
    }
}
